package com.huwaiwai001.echo.bio.client;

import com.huwaiwai001.echo.constant.ServerInfo;
import com.huwaiwai001.echo.util.InputUtil;

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by hww on 2019/3/18 10:58.
 */
public class EchoBioClientHandler implements AutoCloseable {

    private Socket client;

    EchoBioClientHandler() throws Exception {
        this.client = new Socket(ServerInfo.ECHO_HOST, ServerInfo.ECHO_PORT);
        System.out.println("服务器链接启动成功!");
    }

    void handle() throws Exception {
        Scanner scan = new Scanner(this.client.getInputStream());
        PrintStream out = new PrintStream(this.client.getOutputStream());
        scan.useDelimiter("\n");
        boolean flag = true;
        while (flag) {
            String data = InputUtil.getString("请输入要发送的数据信息:");
            out.println(data);
            if ("exit".equalsIgnoreCase(data)) {
                flag = false;
            }
            if (scan.hasNext()) {
                System.out.println(scan.next());
            }
        }
    }

    @Override
    public void close() throws Exception {
        client.close();
    }
}
